package 笔试.thread;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierDemo {
    public static void main(String[] args) {
        int persons = 3;
        CyclicBarrier barrier = new CyclicBarrier(persons);
        for (int i = 0; i < persons; i++) {
            new MyThread("线程-" + (i + 1), barrier).start();
        }
    }

    static class MyThread extends Thread {
        private final CyclicBarrier barrier;
        private final Random random = new Random();

        public MyThread(String name, CyclicBarrier barrier) {
            super(name);
            this.barrier = barrier;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(random.nextInt(2000));
                System.out.println(Thread.currentThread().getName() + " - 已经到达公司");
                barrier.await();
                Thread.sleep(random.nextInt(2000));
                System.out.println(Thread.currentThread().getName() + " - 已经笔试结束");
                barrier.await();
                Thread.sleep(random.nextInt(2000));
                System.out.println(Thread.currentThread().getName() + " - 已经面试结束");
            } catch (Exception e) {
                e.printStackTrace();
            }
            super.run();
        }
    }
}
